package com.jyt.utils;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;

public class soket {


    /**
     * socket连接
     * @param ip 设备IP地址
     * @param port 设备端口号
     * @param order 需要发送的指令<byte>
     * @return
     */
    public static byte[] sock(String ip,int port,byte[] order) { //发送指令返回byte[]
        Socket socket = null;
        OutputStream os = null;
        InputStream in = null;

        // 循环标记
        boolean flag = false;
        byte[] data = new byte[64];
        int len = 0;
        try {
            //新建一个socket
            socket = new Socket();
            //socket连接
            socket.connect(new InetSocketAddress(ip, port));
            socket.setSoTimeout(1000); //设置超时时间
            //向服务器发送数据，使用socket套接字对象中的字节输入流
            os = socket.getOutputStream();
            os.write(order);
            os.flush();

            Thread.sleep(1000);//等待1S 超过1S无返回值 则连接超时
            //读取服务器发回的数据，使用socket套接字对象中的字节输入流
            in = socket.getInputStream();
            data = new byte[24]; //最大24 byte
            len = in.read(data);
            flag = true;

        } catch (ConnectException e) {
            System.out.println("服务器连接异常:" + e);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }  finally {
            closeStream(socket, os, in); //关闭连接
        }
        return data;
    }

    private static void closeStream(Socket socket, OutputStream os, InputStream in) {//关闭连接
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                System.out.println("os关闭异常"+e);
                //logger.error("os关闭异常", e);
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                System.out.println("in关闭异常"+e);
                //logger.error("in关闭异常", e);
            }
        }
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                System.out.println("socket关闭异常"+e);
                //logger.error("socket关闭异常", e);
            }
        }
    }

    /**
     * 将字节数组转成字符串
     *
     * @param bytes
     * @return
     */
    public static String bytesToHexString(byte[] bytes) { //byte[] 转 String
        StringBuilder stringBuilder = new StringBuilder("");
        if (bytes == null || bytes.length <= 0) {
            return null;
        }
        for (int i = 0; i < bytes.length; i++) {
            int v = bytes[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }

            if (i != bytes.length - 1) {
                stringBuilder.append(hv + " ");
            } else {
                stringBuilder.append(hv);
            }
        }
        return stringBuilder.toString();
    }

    /**
     * 16进制<String>转 byte[]
     * @param inHex
     * @return
     */
    public static byte[] hexToByteArray(String inHex) { //string转byte[]
        int hexlen = inHex.length();
        byte[] result;
        if (hexlen % 2 == 1) {
            //奇数
            hexlen++;
            result = new byte[(hexlen / 2)];
            inHex = "0" + inHex;
        } else {
            //偶数
            result = new byte[(hexlen / 2)];
        }
        int j = 0;
        for (int i = 0; i < hexlen; i += 2) {
            result[j] = hexToByte(inHex.substring(i, i + 2));
            j++;
        }
        return result;
    }
    //String转byte
    public static byte hexToByte(String inHex) { //string转byte
        return (byte) Integer.parseInt(inHex, 16);
    }

    /**
     * 16进制转10进制
     * @param strHex
     * @return
     */
    public static int hex16to10(String strHex) { //16进制转10进制
        BigInteger lingNum = new BigInteger(strHex, 16);

        return lingNum.intValue();
    }

    /**
     * 10进制转16进制
     * @param ten
     * @return
     */
    public static String hex10to16(int ten) {
        return String.format("%02X", ten);
    }

    /**
     * 指定字节数组中的第几位转换成String字符串
     * @param bytes
     * @param index
     * @return
     */
    public static String transformByteArrayToString(byte[] bytes, int index) {
        String[] array = bytesToHexString(bytes).split(" ");
        return array[index];
    }

    /**
     * byte转16进制
     * @param bytes
     * @return
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() < 2) {
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString();
    }
}
